package com.example;

import com.example.annotation.FieldAnnotation;
import com.example.annotation.MethodAnnotation;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AnnotationManager {

    public static void initFieldAnnotation(Object currentObj){
        Class clazz = currentObj.getClass();
        Field[] field = clazz.getDeclaredFields();
        for(Field f:field){
            FieldAnnotation fieldAnnotation = f.getAnnotation(FieldAnnotation.class);
            f.setAccessible(true);
            try {
                if(f.isAnnotationPresent(FieldAnnotation.class)){
                    if("java.lang.String".contains(f.getType().getName())){
                        f.set(currentObj,fieldAnnotation.valueStr());
                    }else if("boolean".contains(f.getType().getName())){
                        f.set(currentObj,fieldAnnotation.valueBool());
                    }else if("int".contains(f.getType().getName())){
                        f.set(currentObj,fieldAnnotation.valueInt());
                    }//...
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public static void initMethodAnnotation(Object currentObj){
        Class clazz = currentObj.getClass();
        Method[] method = clazz.getDeclaredMethods();
        for(Method m:method){
            MethodAnnotation methodAnnotation = m.getAnnotation(MethodAnnotation.class);
            if(m.isAnnotationPresent(MethodAnnotation.class)){
                m.setAccessible(true);
                try {
                    m.invoke(currentObj,methodAnnotation.value());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
